<template>
  <a-spin :spinning="loading" tip="加载中...">
    <div class="bom-detail-container">
      <div class="bom-detail-header">
        <div class="bom-detail-title">
          <h2>{{ bomDetail.product_name }} - BOM详情</h2>
          <div class="bom-detail-actions">
            <a-button type="primary" @click="editBom">
              <template #icon><EditOutlined /></template>
              编辑BOM
            </a-button>
            <a-button @click="goBack">
              <template #icon><ArrowLeftOutlined /></template>
              返回
            </a-button>
          </div>
        </div>
      </div>

      <a-tabs v-model:activeKey="activeTab" class="bom-detail-tabs">
        <!-- 基本信息 -->
        <a-tab-pane key="basic" tab="基本信息">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="BOM编码">{{ bomDetail.bom_code }}</a-descriptions-item>
            <a-descriptions-item label="产品名称">{{ bomDetail.product_name }}</a-descriptions-item>
            <a-descriptions-item label="产品SKU">{{ bomDetail.product_sku }}</a-descriptions-item>
            <a-descriptions-item label="BOM类型">{{ bomDetail.bom_type }}</a-descriptions-item>
            <a-descriptions-item label="版本">{{ bomDetail.version }}</a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-tag :color="bomDetail.status === 'active' ? 'green' : 'red'">
                {{ bomDetail.status }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="生命周期状态">
              <a-tag :color="getLifecycleColor(bomDetail.lifecycle_status)">
                {{ bomDetail.lifecycle_status }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="生效日期">{{ bomDetail.effective_date }}</a-descriptions-item>
            <a-descriptions-item label="失效日期">{{ bomDetail.expiry_date }}</a-descriptions-item>
            <a-descriptions-item label="创建人">{{ bomDetail.creator }}</a-descriptions-item>
            <a-descriptions-item label="创建时间">{{ bomDetail.create_time }}</a-descriptions-item>
            <a-descriptions-item label="修改人">{{ bomDetail.modifier }}</a-descriptions-item>
            <a-descriptions-item label="修改时间">{{ bomDetail.update_time }}</a-descriptions-item>
            <a-descriptions-item label="描述" :span="2">{{ bomDetail.description }}</a-descriptions-item>
            <a-descriptions-item label="备注" :span="2">{{ bomDetail.remark }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <!-- BOM组件 -->
        <a-tab-pane key="components" tab="BOM组件">
          <BasicTable @register="registerComponentTable">
            <template #toolbar>
              <a-button type="primary" @click="handleAddComponent">
                <template #icon><PlusOutlined /></template>
                添加组件
              </a-button>
              <a-button type="default" @click="handleExportComponents">
                <template #icon><ExportOutlined /></template>
                导出组件
              </a-button>
            </template>
          </BasicTable>
        </a-tab-pane>

        <!-- 替代物料 -->
        <a-tab-pane key="alternatives" tab="替代物料">
          <BasicTable @register="registerAlternativeTable">
            <template #toolbar>
              <a-button type="primary" @click="handleAddAlternative">
                <template #icon><PlusSquareOutlined /></template>
                添加替代
              </a-button>
            </template>
          </BasicTable>
        </a-tab-pane>

        <!-- 文档管理 -->
        <a-tab-pane key="documents" tab="文档管理">
          <BasicTable @register="registerDocumentTable">
            <template #toolbar>
              <a-button type="primary" @click="handleAddDocument">
                <template #icon><PlusOutlined /></template>
                添加文档
              </a-button>
            </template>
          </BasicTable>
        </a-tab-pane>

        <!-- 版本历史 -->
        <a-tab-pane key="versions" tab="版本历史">
          <BasicTable @register="registerVersionTable">
          </BasicTable>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 组件表单弹窗 -->
    <BasicModal
      v-bind="$attrs"
      @register="registerComponentModal"
      :title="componentModalTitle"
      @ok="handleComponentModalOk"
      :width="800"
    >
      <BasicForm @register="registerComponentForm" />
    </BasicModal>

    <!-- 替代物料表单弹窗 -->
    <BasicModal
      v-bind="$attrs"
      @register="registerAlternativeModal"
      :title="alternativeModalTitle"
      @ok="handleAlternativeModalOk"
      :width="800"
    >
      <BasicForm @register="registerAlternativeForm" />
    </BasicModal>

    <!-- 文档表单弹窗 -->
    <BasicModal
      v-bind="$attrs"
      @register="registerDocumentModal"
      :title="documentModalTitle"
      @ok="handleDocumentModalOk"
      :width="800"
    >
      <BasicForm @register="registerDocumentForm" />
    </BasicModal>

    <!-- 版本表单弹窗 -->
    <BasicModal
      v-bind="$attrs"
      @register="registerVersionModal"
      :title="versionModalTitle"
      @ok="handleVersionModalOk"
      :width="800"
    >
      <BasicForm @register="registerVersionForm" />
    </BasicModal>

    <!-- 批量添加组件弹窗 -->
    <BasicModal
      v-bind="$attrs"
      @register="registerBatchAddModal"
      title="批量添加组件"
      @ok="handleBatchAddModalOk"
      :width="800"
    >
      <BasicForm @register="registerBatchAddForm" />
    </BasicModal>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  EditOutlined,
  ArrowLeftOutlined,
  PlusOutlined,
  PlusSquareOutlined,
  ExportOutlined,
  DeleteOutlined,
  DownloadOutlined,
  RollbackOutlined,
} from '@ant-design/icons-vue';
import { BasicTable, useTable } from '#/adapter/table';
import { BasicModal, useModal } from '@vben/common-ui';
import { BasicForm, useForm } from '@vben/common-ui';
import type { OnActionClickParams } from '#/adapter/vxe-table';

// 导入API和模型
import { bomModel } from '@/models/bom/bom';
// 导入BOM配置
import { bomConfig } from '#/views/bom/data';

// 定义接口
interface BOMDetail {
  id: number;
  bom_code: string;
  product_name: string;
  product_sku: string;
  bom_type: string;
  version: string;
  status: string;
  lifecycle_status: string;
  effective_date: string;
  expiry_date: string;
  description: string;
  remark: string;
  creator: string;
  modifier: string;
  create_time: string;
  update_time: string;
}

// 获取路由参数
const route = useRoute();
const router = useRouter();
const bomId = ref<number>(Number(route.params.id));

// 状态管理
const loading = ref(false);
const error = ref<string | null>(null);
const activeTab = ref('basic');
const bomDetail = ref<BOMDetail>({
  id: 0,
  bom_code: '',
  product_name: '',
  product_sku: '',
  bom_type: '',
  version: '',
  status: '',
  lifecycle_status: '',
  effective_date: '',
  expiry_date: '',
  description: '',
  remark: '',
  creator: '',
  modifier: '',
  create_time: '',
  update_time: '',
});

// 生命周期状态颜色映射
const getLifecycleColor = (status: string) => {
  const colorMap: Record<string, string> = {
    draft: 'default',
    active: 'green',
    pending: 'orange',
    obsolete: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取BOM详情
const getBomDetail = async () => {
  if (!bomId.value) {
    error.value = '无效的BOM ID';
    return;
  }

  loading.value = true;
  error.value = null;
  try {
    const response = await bomModel.retrieve(bomId.value);
    bomDetail.value = response;
  } catch (err) {
    error.value = '获取BOM详情失败';
    message.error('获取BOM详情失败');
    console.error('获取BOM详情错误:', err);
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 编辑BOM
const editBom = () => {
  router.push(`/bom/edit/${bomId.value}`);
};

// 组件相关
const [registerComponentTable, { reload: reloadComponentTable }] = useTable({
  title: 'BOM组件列表',
  api: () => bomModel.getComponents(bomId.value),
  columns: bomConfig.useComponentColumns(),
  pagination: true,
  striped: false,
  useSearchForm: false,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
});

const [registerComponentModal, { openModal: openComponentModal, closeModal: closeComponentModal }] = useModal();
const [registerComponentForm, { setFieldsValue: setComponentFieldsValue, resetFields: resetComponentFields, validate: validateComponentForm }] = useForm({
  labelWidth: 100,
  schemas: bomConfig.useComponentSchema(),
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const componentModalTitle = ref('添加组件');
const currentComponentId = ref<number | null>(null);

const handleAddComponent = () => {
  componentModalTitle.value = '添加组件';
  currentComponentId.value = null;
  resetComponentFields();
  openComponentModal();
};

const handleEditComponent = (record: any) => {
  componentModalTitle.value = '编辑组件';
  currentComponentId.value = record.id;
  setComponentFieldsValue(record);
  openComponentModal();
};

const handleDeleteComponent = async (record: any) => {
  try {
    await bomModel.deleteComponent(bomId.value, record.id);
    message.success('删除成功');
    reloadComponentTable();
  } catch (err) {
    message.error('删除失败');
    console.error('删除组件错误:', err);
  }
};

const handleComponentModalOk = async () => {
  try {
    const values = await validateComponentForm();
    if (currentComponentId.value) {
      await bomModel.updateComponent(bomId.value, currentComponentId.value, values);
      message.success('更新成功');
    } else {
      await bomModel.addComponent(bomId.value, values);
      message.success('添加成功');
    }
    closeComponentModal();
    reloadComponentTable();
  } catch (err) {
    message.error('操作失败');
    console.error('组件操作错误:', err);
  }
};

const handleBatchAddComponents = () => {
  openBatchAddModal();
};

const handleExportComponents = async () => {
  try {
    await bomModel.exportComponents(bomId.value);
    message.success('导出成功');
  } catch (err) {
    message.error('导出失败');
    console.error('导出组件错误:', err);
  }
};

// 替代物料相关
const [registerAlternativeTable, { reload: reloadAlternativeTable }] = useTable({
  title: '替代物料列表',
  api: () => bomModel.getAlternatives(bomId.value),
  columns: bomConfig.useAlternativeColumns(),
  pagination: true,
  striped: false,
  useSearchForm: false,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
});

const [registerAlternativeModal, { openModal: openAlternativeModal, closeModal: closeAlternativeModal }] = useModal();
const [registerAlternativeForm, { setFieldsValue: setAlternativeFieldsValue, resetFields: resetAlternativeFields, validate: validateAlternativeForm }] = useForm({
  labelWidth: 100,
  schemas: bomConfig.useAlternativeSchema(),
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const alternativeModalTitle = ref('添加替代物料');
const currentAlternativeId = ref<number | null>(null);

const handleAddAlternative = () => {
  alternativeModalTitle.value = '添加替代物料';
  currentAlternativeId.value = null;
  resetAlternativeFields();
  openAlternativeModal();
};

const handleEditAlternative = (record: any) => {
  alternativeModalTitle.value = '编辑替代物料';
  currentAlternativeId.value = record.id;
  setAlternativeFieldsValue(record);
  openAlternativeModal();
};

const handleDeleteAlternative = async (record: any) => {
  try {
    await bomModel.deleteAlternative(bomId.value, record.id);
    message.success('删除成功');
    reloadAlternativeTable();
  } catch (err) {
    message.error('删除失败');
    console.error('删除替代物料错误:', err);
  }
};

const handleAlternativeModalOk = async () => {
  try {
    const values = await validateAlternativeForm();
    if (currentAlternativeId.value) {
      await bomModel.updateAlternative(bomId.value, currentAlternativeId.value, values);
      message.success('更新成功');
    } else {
      await bomModel.addAlternative(bomId.value, values);
      message.success('添加成功');
    }
    closeAlternativeModal();
    reloadAlternativeTable();
  } catch (err) {
    message.error('操作失败');
    console.error('替代物料操作错误:', err);
  }
};

// 文档相关
const [registerDocumentTable, { reload: reloadDocumentTable }] = useTable({
  title: '文档列表',
  api: () => bomModel.getDocuments(bomId.value),
  columns: bomConfig.useDocumentColumns(),
  pagination: true,
  striped: false,
  useSearchForm: false,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 180,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
});

const [registerDocumentModal, { openModal: openDocumentModal, closeModal: closeDocumentModal }] = useModal();
const [registerDocumentForm, { setFieldsValue: setDocumentFieldsValue, resetFields: resetDocumentFields, validate: validateDocumentForm }] = useForm({
  labelWidth: 100,
  schemas: bomConfig.useDocumentSchema(),
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const documentModalTitle = ref('添加文档');
const currentDocumentId = ref<number | null>(null);

const handleAddDocument = () => {
  documentModalTitle.value = '添加文档';
  currentDocumentId.value = null;
  resetDocumentFields();
  openDocumentModal();
};

const handleEditDocument = (record: any) => {
  documentModalTitle.value = '编辑文档';
  currentDocumentId.value = record.id;
  setDocumentFieldsValue(record);
  openDocumentModal();
};

const handleDeleteDocument = async (record: any) => {
  try {
    await bomModel.deleteDocument(bomId.value, record.id);
    message.success('删除成功');
    reloadDocumentTable();
  } catch (err) {
    message.error('删除失败');
    console.error('删除文档错误:', err);
  }
};

const handleDownloadDocument = async (record: any) => {
  try {
    await bomModel.downloadDocument(bomId.value, record.id);
    message.success('下载成功');
  } catch (err) {
    message.error('下载失败');
    console.error('下载文档错误:', err);
  }
};

const handleDocumentModalOk = async () => {
  try {
    const values = await validateDocumentForm();
    if (currentDocumentId.value) {
      await bomModel.updateDocument(bomId.value, currentDocumentId.value, values);
      message.success('更新成功');
    } else {
      await bomModel.addDocument(bomId.value, values);
      message.success('添加成功');
    }
    closeDocumentModal();
    reloadDocumentTable();
  } catch (err) {
    message.error('操作失败');
    console.error('文档操作错误:', err);
  }
};

// 版本历史相关
const [registerVersionTable, { reload: reloadVersionTable }] = useTable({
  title: '版本历史列表',
  api: () => bomModel.getVersions(bomId.value),
  columns: bomConfig.useVersionColumns(),
  pagination: true,
  striped: false,
  useSearchForm: false,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 200,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
});

const [registerVersionModal, { openModal: openVersionModal, closeModal: closeVersionModal }] = useModal();
const [registerVersionForm, { setFieldsValue: setVersionFieldsValue, resetFields: resetVersionFields, validate: validateVersionForm }] = useForm({
  labelWidth: 100,
  schemas: bomConfig.useVersionSchema(),
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const versionModalTitle = ref('新建版本');
const currentVersionId = ref<number | null>(null);

const handleAddVersion = () => {
  versionModalTitle.value = '新建版本';
  currentVersionId.value = null;
  resetVersionFields();
  openVersionModal();
};

const handleEditVersion = (record: any) => {
  versionModalTitle.value = '编辑版本';
  currentVersionId.value = record.id;
  setVersionFieldsValue(record);
  openVersionModal();
};

const handleDeleteVersion = async (record: any) => {
  try {
    await bomModel.deleteVersion(bomId.value, record.id);
    message.success('删除成功');
    reloadVersionTable();
  } catch (err) {
    message.error('删除失败');
    console.error('删除版本错误:', err);
  }
};

const handleRollbackVersion = async (record: any) => {
  try {
    await bomModel.rollbackVersion(bomId.value, record.id);
    message.success('回滚成功');
    reloadVersionTable();
    getBomDetail(); // 刷新基本信息
  } catch (err) {
    message.error('回滚失败');
    console.error('回滚版本错误:', err);
  }
};

const handleVersionModalOk = async () => {
  try {
    const values = await validateVersionForm();
    if (currentVersionId.value) {
      await bomModel.updateVersion(bomId.value, currentVersionId.value, values);
      message.success('更新成功');
    } else {
      await bomModel.addVersion(bomId.value, values);
      message.success('添加成功');
    }
    closeVersionModal();
    reloadVersionTable();
  } catch (err) {
    message.error('操作失败');
    console.error('版本操作错误:', err);
  }
};

// 批量添加组件相关
const [registerBatchAddModal, { openModal: openBatchAddModal, closeModal: closeBatchAddModal }] = useModal();
const [registerBatchAddForm, { resetFields: resetBatchAddFields, validate: validateBatchAddForm }] = useForm({
  labelWidth: 100,
  schemas: bomConfig.useBatchAddSchema(),
  showActionButtonGroup: false,
  baseColProps: { lg: 24, md: 24 },
});

const handleBatchAddModalOk = async () => {
  try {
    const values = await validateBatchAddForm();
    await bomModel.batchAddComponents(bomId.value, values);
    message.success('批量添加成功');
    closeBatchAddModal();
    reloadComponentTable();
  } catch (err) {
    message.error('批量添加失败');
    console.error('批量添加组件错误:', err);
  }
};

// 页面加载时获取数据
onMounted(() => {
  getBomDetail();
});
</script>
